<template>
  <div class="comment">
    <van-field
      class="my-field"
      v-model="message"
      rows="2"
      autosize
      label="发表评论"
      type="textarea"
      maxlength="50"
      placeholder="请输入评论"
      show-word-limit
      ref="contentRef"
    />
    <van-button type="primary" block @click="postComments">发表评论</van-button>

    <div class="comment-list">
      <van-card
        :desc="item.content"
        title="商品标题"
        v-for="(item, index) in comments"
        :key="index"
      >
        <template #thumb>
          <div class="user-info">
            <van-icon
              class="user-icon"
              name="https://b.yzcdn.cn/vant/icon-demo-1126.png"
            />
            <div>{{ item.user_name }}</div>
          </div>
        </template>
        <template #title>
          <van-rate v-model="item.rate" readonly />
        </template>
        <template #price> {{ item.add_time }} </template>
      </van-card>
    </div>
    <van-loading size="24px" v-if="isloading">加载中...</van-loading>
    <button v-else class="more" @click="getMore">
      {{ moreText }}
    </button>
  </div>
</template>
<script>
import moment from "moment";
export default {
  props: ["id"],
  computed: {
    moreText() {
      return this.hasMore ? "我也是有底线的" : "加载更多";
    },
  },
  data() {
    return {
      message: "",
      value: 5,
      page: 0,
      limit: 20,
      comments: [],
      hasMore: false,
      isloading: false,
    };
  },
  created() {
    this.getComments();
  },
  methods: {
    async getComments() {
      if (this.hasMore !== false) return;
      ++this.page;
      const res = await this.$http.getComments({
        id: this.id,
        page: this.page,
        limit: this.limit,
      });
      this.comments = [...this.comments, ...res.data.message];
      this.hasMore = this.page * this.limit > res.data.count;
      console.log(this.hasMore);
    },
    getMore() {
      this.isloading = true;
      this.timer = setTimeout(() => {
        this.getComments();
        this.isloading = false;
      }, 500);
    },
    async postComments() {
      if (!this.message) return;
      await this.$http.postComments({ id: this.id, content: this.messages });
      // 写假数据提交
      this.comments.unshift({
        user_name: "匿名用户",
        add_time: moment().format("YYYY-MM-DD HH:mm:ss"),
        content: this.message,
        rate: 5,
      });
      this.message = "";
      this.$refs.contentRef.focus();
    },
  },
};
</script>
<style lang="scss" scoped>
.comment {
  .my-field {
    border: 1px solid #eee;
    margin: 10px 0;
  }
  .comment-list {
    margin-top: 10px;
    .user-icon {
      font-size: 60px;
    }
    .van-card__desc {
      margin-top: 15px;
    }
  }
  .more {
    width: 100%;
    background-color: #fff;
    outline: none;
    border: none;
    color: #969799;
    line-height: 30px;
    font-size: 12px;
    text-align: center;
  }
  .van-loading {
    text-align: center;
  }
}
</style>
